04. Solution: Defining Functions

Quiz Solution: Population Density Function

def population_density(population, land_area):
    return population/land_area

# test cases for your function
test1 = population_density(10, 1)
expected_result1 = 10
print("expected result: {}, actual result: {}".format(expected_result1, test1))

test2 = population_density(864816, 121.4)
expected_result2 = 7123.6902801
print("expected result: {}, actual result: {}".format(expected_result2, test2))

Output:

expected result: 10, actual result: 10.0
expected result: 7123.6902801, actual result: 7123.690280065897

I used a one-line function body because my personal preference is to keep my functions brief, as long as it doesn't make the code confusing. You could also perform the calculation on its own line separate from the return statement.

Quiz Solution: readable_timedelta

def readable_timedelta(days):
    # use integer division to get the number of weeks
    weeks = days // 7
    # use % to get the number of days that remain
    remainder = days % 7
    return "{} week(s) and {} day(s).".format(weeks, remainder)

# test your function
print(readable_timedelta(10))

Output:

1 week(s) and 3 day(s).

Nice work on writing your first functions! You'll see and write more functions soon.